import { parentPort } from 'worker_threads';
import crypto from 'crypto'; // 导入加密模块

const port = parentPort;
if (!port) throw new Error('IllegalState');

port.on('message', (msg) => {
  try {
    console.log('RSAWorker已加载');
    if (msg.method === 'getKeyPair') {
      const RSAKeyPair = getRSAKeyPair(2048);
      port.postMessage(RSAKeyPair);
    }

    if (msg.method === 'encrypt-public-key') {
      const encrypted = encryptWithPublicKey(msg.rsaPublicKey, msg.data);
      port.postMessage({ encrypted });
      console.log('加密完成');
    }

    if (msg.method === 'decrypt-private-key') {
      const decrypted = decryptWithPrivateKey(msg.rsaPrivateKey, msg.data);
      port.postMessage({ decrypted });
    }

    if (msg.method === 'sign-data') {
      const signature = signData(msg.rsaPrivateKey, msg.data);
      port.postMessage({ signature });
    }

    if (msg.method === 'verify-signature') {
      const isValid = verifySignature(
        msg.rsaPublicKey,
        msg.data,
        msg.signature
      );
      port.postMessage({ isValid });
    }
  } catch (error) {
    console.error('rasWorker错误：', error);
    port.postMessage({ error });
  }
});

const signData = (rsaPrivateKey: string, data: string) => {
  const sign = crypto.createSign('SHA256');
  sign.update(data);
  sign.end();
  const signature = sign.sign(rsaPrivateKey, 'base64');
  return signature;
};

const verifySignature = (
  rsaPublicKey: string,
  data: string,
  signature: string
) => {
  const verify = crypto.createVerify('SHA256');
  verify.update(data);
  verify.end();
  const isValid = verify.verify(rsaPublicKey, signature, 'base64');
  return isValid;
};

const decryptWithPrivateKey = (rsaPrivateKey: string, encrypted: string) => {
  const decrypted = crypto.privateDecrypt(
    rsaPrivateKey,
    Buffer.from(encrypted, 'base64')
  );
  return decrypted.toString('utf8');
};

const encryptWithPublicKey = (rsaPublicKey: string, data: string) => {
  const encrypted = crypto.publicEncrypt(rsaPublicKey, Buffer.from(data));
  return encrypted.toString('base64');
};

const getRSAKeyPair = (length: number) => {
  return crypto.generateKeyPairSync('rsa', {
    modulusLength: length,
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'pkcs8',
      format: 'pem'
    }
  });
};
